<template>
  <div>
    <!-- 导入Excel -->
    <el-row style="margin:20px 0;">
      <el-col :span="8"
        ><el-upload
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="onChange"
          :auto-upload="false"
          :show-file-list="false"
          accept=".xls, .xlsx"
        >
          <el-button type="warning" icon="el-icon-folder-add">批量导入</el-button>
        </el-upload>
      </el-col>
      <el-col :span="8"> <el-button type="warning" icon="el-icon-download" @click="exportToExcel">批量导出</el-button></el-col>
      <el-col :span="8">
        <el-button type="primary" @click="add">新增数据</el-button>
      </el-col>
    </el-row>

    <el-table :data="studentlist" style="width: 100%" border stripe>
      <el-table-column prop="id" label="id"> </el-table-column>
      <el-table-column prop="stuNumber" label="学号"> </el-table-column>
      <el-table-column prop="stuName" label="姓名"> </el-table-column>
      <el-table-column prop="sex" label="性别"> </el-table-column>
      <el-table-column prop="tel" label="电话"> </el-table-column>
      <el-table-column prop="xueyuan" label="学院"> </el-table-column>
      <el-table-column prop="banji" label="班级"> </el-table-column>
      <el-table-column prop="lyNumber" label="楼宇号"> </el-table-column>
      <el-table-column prop="sushe" label="宿舍号"> </el-table-column>
    </el-table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      fileData: '',
      outputs: [],
      studentlist: []
    }
  },
  created() {},
  methods: {
    // ----------以下为导入Excel数据功能--------------
    // 文件选择回调
    onChange(file, fileList) {
      console.log('fileList::', fileList)
      this.fileData = file // 保存当前选择文件
      this.readExcel() // 调用读取数据的方法
    },
    // 读取数据
    readExcel(e) {
      console.log('e::', e)
      let that = this
      const files = that.fileData
      console.log('files::', files)
      if (!files) {
        //如果没有文件
        return false
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }
      const fileReader = new FileReader()
      fileReader.onload = ev => {
        try {
          const data = ev.target.result
          // console.log(data)
          const workbook = this.XLSX.read(data, {
            type: 'binary'
          })
          console.log('SheeNames', workbook.SheetNames)
          if (workbook.SheetNames.length >= 1) {
            this.$message({
              message: '导入数据表格成功',
              showClose: true,
              type: 'success'
            })
          }
          const wsname = workbook.SheetNames[0] //取第一张表
          const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
          console.log('ws::', ws)
          that.outputs = [] //清空接收数据
          for (var i = 0; i < ws.length; i++) {
            var sheetData = {
              // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
              id: ws[i]['id'],
              stuNumber: ws[i]['学号'],
              stuName: ws[i]['姓名'],
              sex: ws[i]['性别'],
              tel: ws[i]['电话'],
              xueyuan: ws[i]['学院'],
              banji: ws[i]['班级'],
              lyNumber: ws[i]['楼宇号'],
              sushe: ws[i]['宿舍号']
            }
            that.studentlist.unshift(sheetData)
            console.log('studentlist', this.studentlist)
          }
          this.$refs.upload.value = ''
        } catch (e) {
          return false
        }
      }
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw)
    },

    //  ----------以下为导出Excel数据功能(导出的是当前页面的数据)--------------
    exportToExcel() {
      //excel数据导出
      require.ensure([], () => {
        const { export_json_to_excel } = require('./excel/Export2Excel')
        const tHeader = ['id', '学号', '姓名', '性别', '电话', '学院', '班级', '楼宇号', '宿舍号']
        const filterVal = ['id', 'stuNumber', 'stuName', 'sex', 'tel', 'xueyuan', 'banji', 'lyNumber', 'sushe']
        const list = this.studentlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, '学生列表excel')
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    add() {
      var params = {
        id: 2,
        stuNumber: '0104180423',
        stuName: '宋蝶二',
        sex: '女',
        tel: '18475969044',
        xueyuan: '计算机学院',
        banji: '18网络2班',
        lyNumber: '6',
        sushe: '604'
      }
      this.studentlist.push(params)
    },

    // //  ----------以下为导出Excel数据功能(导出后端返回的Blob文件对象)--------------
    downloadRequest({ url, params, file, method, defName }) {
      if (this.isStartWith(url, ['http://', 'https://', '//'])) {
      } else {
        //打包发布的时候加上
        url = this.api.PathRoot + url
      }

      if (!params && (!method || method == 'GET')) {
        this.downloadFile(file, null, url)
        return
      }

      method = method || 'GET'

      let requestObj = {
        method,
        url,
        responseType: 'blob'
      }

      if (method == 'GET') {
        requestObj.params = params
      } else {
        requestObj.data = params
        requestObj.headers = {
          'Content-Type': 'application/json'
        }
      }

      this.apiClient()(requestObj).then(response => {
        if (!file) {
          let contentDisposition = response.headers['content-disposition'] || defName || `${Date.now()}`
          let name = contentDisposition.replace('attachment;filename=', '')
          name = decodeURI(name)
          file = {
            name
          }
        }
        this.downloadFile(file, response.data)
      })
    },

    downloadFile(file, raw, url) {
      var a = document.createElement('a')
      a.setAttribute('target', '_blank')
      a.download = file && (file.originName || file.name)

      if (raw) {
        url = window.URL.createObjectURL(raw)
      }

      a.href = url
      a.click()

      if (raw) {
        window.URL.revokeObjectURL(url)
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
